package com.maxdu.labs.stt.models.db;

import java.util.List;

import android.util.Log;

import com.maxdu.labs.stt.constants.Constants;
import com.maxdu.labs.stt.models.User;
import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.SaveCallback;

public class UserDBHelper {

	private final String PARSE_DB_TABLENAME_USERS = "UserParseObject";
	private final String PARSE_DB_FIELD_USERID = "userId";
	private final String PARSE_DB_FIELD_NAME = "name";
	private ParseObject userParseObject;
	private User user;
	
	public UserDBHelper(){
		userParseObject = new ParseObject (PARSE_DB_TABLENAME_USERS);
	}
	
	public void updateToCloud(User arg){
		
		this.user = arg;
		
		if(user != null){
			userParseObject.put(PARSE_DB_FIELD_USERID, user.getUserId());
			if(user.getName() != null){
				userParseObject.put(PARSE_DB_FIELD_NAME, user.getName());
			}else{
				Log.w(Constants.LOG_TAG, "UserDBHelper::updateToCloud() - updating an user with a getName() == NULL");
			}
			userParseObject.saveInBackground(new SaveCallback() {
				
				@Override
				public void done(ParseException e) {
					if (e == null){
						Log.d(Constants.LOG_TAG, "we successfully updated to Cloud the user: " + user.getUserId());
					}else{
						Log.w(Constants.LOG_TAG, "PROBLEM when trying to update the user [" + user.getUserId() + "] to Cloud. errorMessage:: " + e);
					}
					
				}
			});
		}else{
			Log.e(Constants.LOG_TAG, "UserDBHelper::updateToCloud() :: USER IS NULL");
		}
	}
	
	public User getUserFromCloud(final String userId){
		
		//TODO clean this sh**... sure there is a better way to do so!
		
		ParseQuery<ParseObject> query = ParseQuery.getQuery(PARSE_DB_TABLENAME_USERS);
		query.whereEqualTo(PARSE_DB_FIELD_USERID, userId);
		
		query.findInBackground(new FindCallback<ParseObject>() {
		    public void done(List<ParseObject> users, ParseException e) {
		        if (e == null) {
		        	if (users.size() > 0){
		        		user = populateUser(users.get(0));
		        		Log.d(Constants.LOG_TAG, "we successfully retrieved from Cloud the user: " + user.getUserId());
		        	}else{
		        		Log.w(Constants.LOG_TAG, "WARNING: we tried to get this User [" + userId + "] from cloud but the results list is EMPTY");
		        	}
		        } else {
		            Log.e(Constants.LOG_TAG, "Error: " + e.getMessage());
		        }
		    }
		});
		
		return user;
	}
	
	private User populateUser(ParseObject userPO){
		return new User(userPO.getString(PARSE_DB_FIELD_USERID), userPO.getString(PARSE_DB_FIELD_NAME), userPO.getCreatedAt(),userPO.getUpdatedAt());
	}
}
